<template>
  <div class="image-chat-container mb-10">
    <div class="flex justify-center items-center">
      <img src="./新品宣导.svg" class="w-64 mt-2 mb-0" alt="" />
    </div>
    <h1 class="font-bold text-2xl text-center mb-1">工业场景缺陷检测</h1>
    <h1 class="text-lg font-light text-gray-400 text-center mb-7">
      Defect detection in industrial scenarios
    </h1>

    <div class="main-content lg:px-20 px-4">
      <!-- 左侧图片上传区域 -->
      <div class="image-section">
        <div
          class="bg-gray-100 border border-gray-200 flex flex-col justify-center items-center p-4 rounded-xl"
        >
          <div v-if="filePreview" class="image-preview mb-5">
            <img
              :src="filePreview.url"
              alt="Preview"
              class="preview-image"
              style="max-height: 200px"
            />
          </div>
          <div v-else class="image-preview mb-5">
            <div class="py-8 text-gray-400">请点击下方按钮，选择所需要问答的图片</div>
          </div>
          <div class="flex items-center mb-6">
            <input
              type="file"
              accept="image/*"
              @change="handleFileUpload"
              ref="fileInput"
              class="file-input"
            />
            <button
              @click="triggerFileInput"
              class="hover:opacity-50 transition bg-blue-500 cursor-pointer font-bold text-white border border-blue-500 ml-3 px-10 py-3 rounded-xl flex items-center"
            >
              <svg
                t="1756978761966"
                class="icon mr-1"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="2479"
                width="20"
                height="20"
              >
                <path
                  d="M938.666667 553.92V768c0 64.8-52.533333 117.333333-117.333334 117.333333H202.666667c-64.8 0-117.333333-52.533333-117.333334-117.333333V256c0-64.8 52.533333-117.333333 117.333334-117.333333h618.666666c64.8 0 117.333333 52.533333 117.333334 117.333333v297.92z m-64-74.624V256a53.333333 53.333333 0 0 0-53.333334-53.333333H202.666667a53.333333 53.333333 0 0 0-53.333334 53.333333v344.48A290.090667 290.090667 0 0 1 192 597.333333a286.88 286.88 0 0 1 183.296 65.845334C427.029333 528.384 556.906667 437.333333 704 437.333333c65.706667 0 126.997333 16.778667 170.666667 41.962667z m0 82.24c-5.333333-8.32-21.130667-21.653333-43.648-32.917333C796.768 511.488 753.045333 501.333333 704 501.333333c-121.770667 0-229.130667 76.266667-270.432 188.693334-2.730667 7.445333-7.402667 20.32-13.994667 38.581333-7.68 21.301333-34.453333 28.106667-51.370666 13.056-16.437333-14.634667-28.554667-25.066667-36.138667-31.146667A222.890667 222.890667 0 0 0 192 661.333333c-14.464 0-28.725333 1.365333-42.666667 4.053334V768a53.333333 53.333333 0 0 0 53.333334 53.333333h618.666666a53.333333 53.333333 0 0 0 53.333334-53.333333V561.525333zM320 480a96 96 0 1 1 0-192 96 96 0 0 1 0 192z m0-64a32 32 0 1 0 0-64 32 32 0 0 0 0 64z"
                  fill="#ffffff"
                  p-id="2480"
                ></path>
              </svg>
              1. 选择图片
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧问答区域 -->
      <div class="chat-section">
        <div class="flex">
          <textarea
            name=""
            v-model="question"
            class="h-24 outline-gray-200 border-gray-200 border-2 px-3 py-2 rounded-xl flex-1"
            id=""
            cols="30"
            rows="10"
          ></textarea>
        </div>
        <div class="question-section">
          <div class="text-gray-400">{{ filePreview ? "✅ 图片已上传" : "图片未上传" }}</div>
          <button
            @click="askQuestion"
            :disabled="!filePreview || loading"
            class="ask-button cursor-pointer"
          >
            2. 点击识别
          </button>
        </div>

        <div class="answer-container">
          <div v-if="answer" class="answer-section">
            <div class="answer-content">
              <div
                v-html="renderedAnswer"
                class="markdown-content"
                style="white-space: pre-line"
              ></div>
            </div>
          </div>

          <!-- Loading动画 -->
          <div v-if="loading" class="flex justify-center my-8">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
          </div>
        </div>

        <div v-if="uploadError" class="error-section">
          <p class="error-message">{{ uploadError }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onUnmounted, computed } from "vue";
  import MarkdownIt from "markdown-it";

  // 响应式数据
  const fileInput = ref(null);
  const imageFile = ref(null);
  const filePreview = ref(null);
  const question = ref(`请你针对这张关于工业场景的图片进行缺陷检测`);
  const answer = ref("");
  const loading = ref(false);
  const uploadError = ref("");

  // 创建markdown-it实例
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
  });

  const renderedAnswer = computed(() => {
    return md.render(answer.value || "");
  });

  // 事件处理器
  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    if (file && file.type.startsWith("image/")) {
      imageFile.value = file;
      filePreview.value = {
        url: URL.createObjectURL(file),
        name: file.name,
        type: "image",
      };
      answer.value = "";
      uploadError.value = "";
    }
  };

  const triggerFileInput = () => {
    fileInput.value.click();
  };

  const askQuestion = async () => {
    if (!imageFile.value) return;

    answer.value = "";
    loading.value = true;
    uploadError.value = "";

    try {
      // 第一步：上传图片
      const formData = new FormData();
      formData.append("file", imageFile.value);

      const uploadResponse = await fetch("/api/upload-image", {
        method: "POST",
        body: formData,
      });

      if (!uploadResponse.ok) {
        throw new Error(`图片上传失败: HTTP ${uploadResponse.status}`);
      }

      const uploadResult = await uploadResponse.json();
      const imageUrl = uploadResult.url;

      // 第二步：使用图片URL进行问答
      const chatResponse = await fetch("/api/chat-with-image", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          image_url: imageUrl,
          prompt: question.value + ", 回答请尽可能写成一段文本",
        }),
      });

      if (!chatResponse.ok) {
        throw new Error(`问答请求失败: HTTP ${chatResponse.status}`);
      }

      if (!chatResponse.body) {
        throw new Error("当前浏览器不支持流式响应");
      }

      const reader = chatResponse.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer = decoder.decode(value, { stream: true });

        if (buffer === "[DONE]") {
          buffer = "";
          break;
        }
        if (buffer.indexOf("[DONE]") !== -1) {
          buffer = buffer.replace("[DONE]", "").trim();
        }
        buffer = buffer.replace("data:", "").trim();
        buffer = buffer.replace("data:", "").trim();
        buffer = buffer.replace("data:", "").trim();
        buffer = buffer.replace("data:", "").trim();
        buffer = buffer.replace("\n", "").trim();
        buffer = buffer.replace("\n", "").trim();
        buffer = buffer.replace("\n", "").trim();
        answer.value += buffer.trim();
      }
    } catch (error) {
      console.error("Error asking question:", error);
      uploadError.value = error.message || "获取回答时出错，请重试。";
      answer.value = "";
    } finally {
      loading.value = false;
    }
  };

  // 清理资源
  onUnmounted(() => {
    if (filePreview.value && filePreview.value.url && filePreview.value.url.startsWith("blob:")) {
      URL.revokeObjectURL(filePreview.value.url);
    }
  });
</script>

<style scoped>
  .image-chat-container {
    margin: 0 auto;
    margin-bottom: 100px;
  }

  .main-content {
    display: flex;
    gap: 30px;
  }

  .image-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .chat-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .file-input {
    display: none;
  }

  .upload-button,
  .submit-button,
  .ask-button {
    padding: 10px 20px;
    border: none;
    border-radius: 100px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s;
  }

  .upload-button {
    background-color: #f0f0f0;
    color: #333;
  }

  .upload-button:hover {
    background-color: #e0e0e0;
  }

  .submit-button,
  .ask-button {
    background-color: #007bff;
    color: white;
  }

  .submit-button:hover,
  .ask-button:hover {
    background-color: #0056b3;
  }

  .submit-button:disabled,
  .ask-button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  .image-preview {
    text-align: center;
  }

  .preview-image {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
  }

  .question-section {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .answer-container {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .answer-section {
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
    flex: 1;
  }

  .answer-section h3 {
    margin-top: 0;
    color: #333;
  }

  .answer-content {
    min-height: 50px;
  }

  .error-section {
    padding: 15px;
    background-color: #f8d7da;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    color: #721c24;
  }

  .error-message {
    margin: 0;
  }

  @media (max-width: 768px) {
    .main-content {
      flex-direction: column;
    }

    .upload-button,
    .submit-button,
    .ask-button {
      width: 100%;
    }
  }
</style>
